const path = require('path')
const Koa = require('koa')
const serve = require('koa-static')
const Router = require('koa-router')
const session = require('koa-session')
const bodyParser = require('koa-bodyparser')
const views = require('koa-views')
const moment = require('moment')
const mongoose = require('mongoose')

const config = require('./config/config')
const { connect, initSchemas } = require('./app/database/init')

;(async () => {
  await connect(config.db)

  initSchemas()

  const { getWechat } = require('./wechat')
  const menu = require('./wechat/menu')
  const client = getWechat()

  try {
    await client.delMenu()
    await client.createMenu(menu)
  } catch (err) {
    console.log(err)
  }

  const app = new Koa()
  const router = new Router()
  const User = mongoose.model('User')

  app.use(views(path.resolve(__dirname, './app/views'), {
    extension: 'pug',
    options: {
      moment: moment
    }
  }))

  app.keys = ['imooc']
  app.use(session(app))
  app.use(bodyParser())
  app.use(serve('../../_public'))

  app.use(async (ctx, next) => {
    const user = ctx.session.user

    if (user && user._id) {
      ctx.session.user = await User.findOne({ _id: user._id })
      ctx.state = Object.assign(ctx.state, {
        user: ctx.session.user
      })
    } else {
      ctx.session.user = null
    }

    await next()
  })

  require('./config/routes')(router)

  app
    .use(router.routes())
    .use(router.allowedMethods())

  app.listen(config.port)
  console.log('Listening: ' + config.port)
})()
